import { Component, EventEmitter, Injector, Input, OnInit, Output, } from '@angular/core';
import { AppLocalizationService } from '@app/shared/common/localization/app-localization.service';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { FileUploadHelper } from '@shared/helpers/FileUploadHelper';
import { TaxonomyItemDataOut,
    TaxonomyServiceProxy,
    CreateTaxonomyItemInput,
    UpdateTaxonomyItemInput} from '@shared/service-proxies/service-proxies';
import { TokenService } from 'abp-ng2-module';
import { map as _map } from 'lodash-es';
import { FileUploader } from 'ng2-file-upload';
import { finalize } from 'rxjs/operators';


@Component({
    selector: 'add-taxonomy-item',
    templateUrl: './add-taxonomy-item.component.html',
})
export class AddTaxonomyItemComponent extends AppComponentBase implements OnInit{

    @Output() taxonomyItemCreated: EventEmitter<TaxonomyItemDataOut> = new EventEmitter<TaxonomyItemDataOut>();
    @Output() taxonomyItemUpdated: EventEmitter<TaxonomyItemDataOut> = new EventEmitter<TaxonomyItemDataOut>();

    saving = false;
    multiLocal = false;
    parentDisplayName : string = '';

    @Input() typeId :string = null;

    get taxonomyItemData(): TaxonomyItemDataOut {
        return this._taxonomyItemData;
    }

    set taxonomyItemData(ou: TaxonomyItemDataOut) {
        if (!ou) {
            this.resetData();
            return;
        }

        let item = new TaxonomyItemDataOut();
        Object.assign(item,ou);
        this._taxonomyItemData = item; 
    }
    
    private _taxonomyItemData: TaxonomyItemDataOut;

    picUploader1: FileUploader;
    picUploader2: FileUploader;

    constructor(
        injector: Injector,
        private _tokenService: TokenService,
        private _taxonomyService: TaxonomyServiceProxy,
        private _appLocalizationService: AppLocalizationService
    ) {
        super(injector);
        this.resetData();
    }

    private resetData(){
        this._taxonomyItemData = new TaxonomyItemDataOut();
        this._taxonomyItemData.typeId = this.typeId;

        this.initUploaders();
    }

    ngOnInit(): void {
        
    }

    private initUploaders(): void {
        this.picUploader1 = FileUploadHelper.createUploader(
            '/B/FileUpload/FileUploadDealTwo',
            ()=> this._tokenService.getToken(),
            result => {
                this.notify.info(this.l('SavedSuccessfully'));
                this._taxonomyItemData.pic1 = result.imgUrl;
            },
            error=>{
                this.notify.error(error.message);
            },
            form=>{
                form.append('customKey', 'singlePictureUpload');
                form.append('uploadType', 0);
            }
        );
        this.picUploader2 = FileUploadHelper.createUploader(
            '/B/FileUpload/FileUploadDealTwo',
            ()=> this._tokenService.getToken(),
            result => {
                this.notify.info(this.l('SavedSuccessfully'));
                this._taxonomyItemData.pic2 = result.imgUrl;
            },
            error=>{
                this.notify.error(error.message);
            },
            form=>{
                form.append('customKey', 'singlePictureUpload');
                form.append('uploadType', 0);
            }
        );
    }

    onPictureInputChange1(event: any) {
        if (this.picUploader1.isUploading) {
            event.target.value = null;
            return;
        }

        if (event.target.files && event.target.files.length > 0) {
            let file = event.target.files[0];
            event.target.value = null;
            if (!FileUploadHelper.check(file.name, 'jpg|jpeg|png|svg', file.size, 2, this.notify, this._appLocalizationService)) {
                this.picUploader1.addToQueue([file]);
            }
        }

        if (this.picUploader1.queue.length > 0) {
            this.picUploader1.uploadAll();
        }
    }
    onPictureInputChange2(event: any) {
        if (this.picUploader2.isUploading) {
            event.target.value = null;
            return;
        }

        if (event.target.files && event.target.files.length > 0) {
            let file = event.target.files[0];
            event.target.value = null;
            if (!FileUploadHelper.check(file.name, 'jpg|jpeg|png|svg', file.size, 2, this.notify, this._appLocalizationService)) {
                this.picUploader2.addToQueue([file]);
            }
        }

        if (this.picUploader2.queue.length > 0) {
            this.picUploader2.uploadAll();
        }
    }

    getUrl(url: string) {
        return FileUploadHelper.getUrl(url);
    }

    lookOver(picurl:string) {
        abp.event.trigger(AppConsts.EventName.showImageView, FileUploadHelper.getUrl(picurl));
    }
    
    save(): void {
        if (!this._taxonomyItemData.id) {
            this.addMenu();
        } else {
            this.updateMenu();
        }
    }
    
    private addMenu(): void {
        const input = new CreateTaxonomyItemInput({
            typeId : this._taxonomyItemData.typeId,
            parentId : this._taxonomyItemData.parentId,
            displayName: this._taxonomyItemData.displayName,
            localDisplayName: this._taxonomyItemData.localDisplayName,
            value: this._taxonomyItemData.value,
            norder:this._taxonomyItemData.norder,
            isActive: this._taxonomyItemData.isActive,
            code: this._taxonomyItemData.code,
            isBindItem: this._taxonomyItemData.isBindItem,
            pic1:this._taxonomyItemData.pic1,
            pic2:this._taxonomyItemData.pic2,
            linkUrl: this._taxonomyItemData.linkUrl
        });
        
        this.saving = true;
        this._taxonomyService
            .createTaxonomyItem(input)
            .pipe(finalize(() => this.saving = false))
            .subscribe((result:TaxonomyItemDataOut) => {
                this.notify.success(this.l('SuccessfullyAdded'));
                this._taxonomyItemData = result;
                this.taxonomyItemCreated.emit(result);
            });
    }

    private updateMenu(): void {
        const input = new UpdateTaxonomyItemInput({
            displayName: this._taxonomyItemData.displayName,
            localDisplayName: this._taxonomyItemData.localDisplayName,
            value: this._taxonomyItemData.value,
            norder:this._taxonomyItemData.norder,
            isActive: this._taxonomyItemData.isActive,
            code: this._taxonomyItemData.code,
            isBindItem: this._taxonomyItemData.isBindItem,
            id: this._taxonomyItemData.id,
            pic1:this._taxonomyItemData.pic1,
            pic2:this._taxonomyItemData.pic2,
            linkUrl: this._taxonomyItemData.linkUrl
        });
        this.saving = true;
        this._taxonomyService
            .updateTaxonomyItem(input)
            .pipe(finalize(() => this.saving = false))
            .subscribe((result:TaxonomyItemDataOut) => {
                this.notify.success(this.l('SavedSuccessfully'));
                this._taxonomyItemData = result;
                this.taxonomyItemUpdated.emit(result);
            });
    }

    close() {
        this.resetData();
    }
}
